package studio.xiaoyun.core.xstream;

import com.thoughtworks.xstream.converters.basic.AbstractSingleValueConverter;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import studio.xiaoyun.core.exception.XyException;

import java.text.ParseException;
import java.util.Date;

/**
 * 实现Date和字符串之间的转换
 */
public class CustomDateConverter extends AbstractSingleValueConverter {
    private String pattern;
    /**
     *
     * @param pattern 字符串的模式
     */
    public CustomDateConverter(String pattern) {
        this.pattern = pattern;
    }

    @Override
    public boolean canConvert(Class type) {
        return type == Date.class;
    }

    @Override
    public Object fromString(String str) {
        try {
            return DateUtils.parseDate(str,pattern);
        } catch (ParseException e) {
            throw new XyException("将字符串转换为日期出错,字符串:"+str,e);
        }
    }

    @Override
    public String toString(Object obj) {
        return DateFormatUtils.format((Date)obj,pattern);
    }
}
